package com.alex.action;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import com.alex.model.Cart;
import com.alex.service.IGoodsService;
import com.alex.service.IOrderService;
import com.alex.entity.Goods;
import com.alex.entity.Orderitem;
import com.alex.entity.Orders;
import com.alex.entity.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ShoppingAction extends ActionSupport {
	private Integer goodsid;
	private int quantity;
	private IGoodsService goodsService;
	private IOrderService orderService;
	
	public String addToCart() throws Exception{
		Goods goods=goodsService.getGoodsById(goodsid);
		Orderitem orderitem=new Orderitem();
		orderitem.setGoods(goods);
		orderitem.setQuantity(quantity);
		Map session=ActionContext.getContext().getSession();
		Cart cart=(Cart)session.get("cart");
		if(cart==null){
			cart=new Cart();
		}
		cart.addGoods(goodsid, orderitem);
		session.put("cart",cart);
		return SUCCESS;
	}
	public String updateCart() throws Exception{
		Map session=ActionContext.getContext().getSession();
		Cart cart=(Cart)session.get("cart");
		cart.updateCart(goodsid, quantity);
		session.put("cart", cart);
		return SUCCESS;
	}
	public String checkout() throws Exception{
		Map session=ActionContext.getContext().getSession();
		User user=(User)session.get("user");
		Cart cart=(Cart)session.get("cart");
		if(user==null || cart ==null)
			return ActionSupport.ERROR;
		
		Orders order=new Orders();
		order.setOrderdate(new Date());
		order.setUser(user);
		for(Iterator it =cart.getItems().values().iterator();it.hasNext();){
		   Orderitem orderitem=(Orderitem)it.next();
		   orderitem.setOrders(order);
		   order.getOrderitems().add(orderitem);
		}
		orderService.saveOrder(order);
		
		Map request=(Map)ActionContext.getContext().get("request");
		request.put("order",order);
		
		return SUCCESS;
	}
	public Integer getGoodsid() {
		return goodsid;
	}
	public void setGoodsid(Integer goodsid) {
		this.goodsid = goodsid;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public IGoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(IGoodsService goodsService) {
		this.goodsService=goodsService;
	}
	public IOrderService getOrderService() {
		return orderService;
	}
	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}
	
}
